import {
  AmbientLight,
  AxesHelper,
  BoxGeometry,
  CanvasTexture,
  Color,
  CubeTexture,
  CubeTextureLoader,
  DataTexture,
  DirectionalLight,
  GridHelper,
  Group,
  LinearFilter,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera,
  PMREMGenerator,
  RGBAFormat,
  Scene,
  Texture,
  TextureLoader,
  Vector3,
  WebGLRenderer,
} from "three";

import {
  GLTFLoader,
  OrbitControls,
  RoomEnvironment,
} from "three/examples/jsm/Addons.js";

function createColorTexture(color, size = 64) {
  const canvas = document.createElement("canvas");
  canvas.width = size; // 或者其他你需要的尺寸
  canvas.height = size;
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = color;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  const texture = new CanvasTexture(canvas); // 设置Texture的过滤方式（可选）
  texture.needsUpdate = true; // 标记Texture需要更新
  texture.minFilter = LinearFilter; // 缩小过滤器
  texture.magFilter = LinearFilter; // 放大过滤器

  return texture;
}

export default class Y3DEngine {
  constructor(options) {
    this.options = options || {};
    this.init();
    this.animate();
  }

  init() {
    this.initRenderer();
    this.initScene();
    this.initCamera();
    this.initLight();
    this.initObject();
    this.initControl();
    this.initHelper();
    this.initEvent();
  }

  get width() {
    return window.innerWidth;
  }

  get height() {
    return window.innerHeight;
  }

  get aspect() {
    return this.width / this.height;
  }

  initScene() {
    this.scene = new Scene();
    if (this.options.environment) {
      // const pmremGenerator = new PMREMGenerator(this.renderer);
      // this.scene.environment = pmremGenerator.fromScene(
      //   new RoomEnvironment(),
      //   0.0001
      // ).texture;
    } else {
      const url = "px180.png";
      const cubeTexture = new CubeTextureLoader()
        .setPath("../assets/")
        .load([url, url, url, url, url, url]);
      this.scene.environment = cubeTexture;
    }
  }

  initCamera() {
    this.camera = new PerspectiveCamera(75, this.aspect, 0.1, 100000);
    this.camera.position.z = 3;
  }

  initRenderer() {
    this.renderer = new WebGLRenderer({ antialias: true });
    this.renderer.setSize(this.width, this.height);
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setClearColor(0x312c42, 1);
    document.body.appendChild(this.renderer.domElement);
  }

  initLight() {
    this.lights = new Group();
    this.scene.add(this.lights);
    const ambientLight = new AmbientLight(0xffffff, 0.3);
    this.lights.add(ambientLight);

    this.light1 = new DirectionalLight(0xffffff, 0.7);
    this.light1.position.set(0, 1, 1);
    this.lights.add(this.light1);

    this.light2 = new DirectionalLight(0xffffff, 0.5);
    this.light2.position.set(0, 1, -1);
    this.lights.add(this.light2);

    this.light3 = new DirectionalLight(0x909090, 0.3);
    this.light3.position.set(0, -1, 0);
    this.lights.add(this.light3);
  }

  initObject() {
    this.model = new Group();
    this.scene.add(this.model);
  }

  loadGLTF = (url, factor = 0.001) => {
    const loader = new GLTFLoader();
    loader.load(url, (gltf) => {
      gltf.scene.scale.set(factor, factor, factor);
      const position = gltf.scene.children[
        parseInt(gltf.scene.children.length / 2)
      ].position
        .clone()
        .multiplyScalar(factor);
      const camPosition = new Vector3(0, 5, 5);
      if (factor < 1) {
        camPosition.multiplyScalar(10);
      }
      camPosition.add(position);
      this.camera.position.copy(camPosition);
      console.log(position, camPosition);
      this.controls.target.copy(position);
      this.model.add(gltf.scene);
      this.controls.update();
    });
  };

  initControl() {
    this.controls = new OrbitControls(this.camera, this.renderer.domElement);
  }

  initHelper() {
    this.helper = new Group();
    this.scene.add(this.helper);
    const gridHelper = new GridHelper(10, 10);
    this.helper.add(gridHelper);
    const axesHelper = new AxesHelper(5);
    this.helper.add(axesHelper);
  }

  initEvent() {
    window.addEventListener("resize", this.onWindowResize);
  }

  onWindowResize = () => {
    this.camera.aspect = this.aspect;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize(this.width, this.height);
  };

  animate = () => {
    requestAnimationFrame(this.animate);
    this.renderer.render(this.scene, this.camera);
  };
}

window.addEventListener("DOMContentLoaded", () => {
  const y3d = new Y3DEngine({ environment: false });
  let url = "../assets/混凝土万能试验机.glb";
  let factor = 1;
  // url = "../assets/钢筋力学万能试验机.glb";
  if (1) {
    url = "../assets/茅草街大桥2.glb";
    url = "../assets/芙蓉镇大桥20240614.glb";
    factor = 0.001;
  }
  y3d.loadGLTF(url, factor);
  console.log(y3d);
  window.y3d = y3d;
});
